<?php

namespace App\Http\Controllers;

use App\Exports\RedFormExport;
use App\Models\RedForm;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use PHPMailer\PHPMailer\PHPMailer;

class MailController extends Controller
{
    private $Mail = null;
    private $Setting = null;

    public function __construct()
    {
        $this->Setting = $this->getConfig();
        $this->Mail = new PHPMailer();
        $this->Mail->isSMTP();
        $this->Mail->Host = 'smtp.qq.com';
        $this->Mail->SMTPAuth = true;
        $this->Mail->Username = $this->Setting->message->email;
        $this->Mail->Password   = $this->Setting->message->email_password;
        $this->Mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $this->Mail->Port = 465;
        $this->Mail->CharSet = "utf8";
        $this->Mail->setFrom($this->Setting->message->email,$this->Setting->message->email_username);
    }

    /**
     *发送红包表单数据到指定邮箱
     */
    public function RedForm($_red_id,Request $request)
    {
        try{
            if(!RedForm::where("red_id",$_red_id)->exists()) {
                throw new \Exception('没有红包表单数据',402);
            }
            $this->Mail->addAddress($request->email);
            $_filename = 'excel/red-form-'.Str::random(8).'.xlsx';
            \Maatwebsite\Excel\Facades\Excel::store(new RedFormExport($_red_id),$_filename);
            $_filename = storage_path('app/public/'.$_filename);
            $this->Mail->Subject = $this->Setting->website_name.'-红包表单';
            $this->Mail->Body = $this->Setting->website_name.'-红包表单';
            $this->Mail->addAttachment($_filename, '红包表单.xlsx');
            $this->Mail->send();
            @unlink($_filename);
        }catch (\Exception $e) {
            return response(['message'=>$e->getMessage()],$e->getCode());
        }
    }

    /**
     * 系统通用邮件发送
     * @param $_send_email
     * @param $_title
     * @param $_body
     * @param bool $_is_html 内容是否html
     * @return bool
     */
    public function send($_send_email,$_title,$_body,$_is_html = false)
    {
        try{
            if($_is_html) {
                $this->Mail->isHTML(true);
            }
            $this->Mail->addAddress($_send_email);
            $this->Mail->Subject = $_title;
            $this->Mail->Body = $_body;
            $this->Mail->send();
            return true;
        }catch (\Exception $e) {
            return false;
        }
    }
}
